package com.zyb.patient.activity;

import java.util.LinkedHashMap;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zyb.patient.R;
import com.zyb.patient.dto.UserDto;
import com.zyb.patient.service.DbSqliteService;
import com.zyb.patient.service.Task;
import com.zyb.patient.util.AppUtils;
import com.zyb.patient.util.Constant;
import com.zyb.patient.util.LogUtil;

public class UserLoginActivity extends BaseActivity implements OnClickListener {

	private EditText phoneEt, codeEt;
	private Button loginBtn, codeBtn;
	private TextView codeTv;
	private String source; //

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_login);

		source = getIntent().getStringExtra("source");
		initView();

		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);
	}

	private void initView() {
		phoneEt = (EditText) findViewById(R.id.user_login_phone_et);
		codeEt = (EditText) findViewById(R.id.user_login_code_et);
		codeBtn = (Button) findViewById(R.id.user_code_btn);
		loginBtn = ((Button) findViewById(R.id.user_login_btn));
		codeBtn.setOnClickListener(this);
		loginBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.user_code_btn) {
			goGetCode();
		} else if (id == R.id.user_login_btn) {
			goLogin();
		}
	}

	/** 获取验证码 **/
	private void goGetCode() {
		String phone = String.valueOf(phoneEt.getText());
		if (TextUtils.isEmpty(phone)) {
			showToast("手机号码不能为空");
			phoneEt.setFocusable(true);
			return;
		}

		if ((phone.length() != 11)) {
			showToast("请输入正确的手机号码(11位)");
			phoneEt.setFocusable(true);
			return;
		}

		// mobile_No（手机号，必填）、device_code（设备码，必填）
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "main/get_sms_captcha");
		map.put("device_code", AppUtils.getmDeviceID());
		map.put("mobile_No", phone);
		getData(map, Task.GET_CODE);
	}

	/** 登录 **/
	private void goLogin() {
		String phone = String.valueOf(phoneEt.getText());
		String code = String.valueOf(codeEt.getText());
		if (TextUtils.isEmpty(phone)) {
			showToast("手机号码不能为空");
			phoneEt.setFocusable(true);
			return;
		}

		if ((phone.length() != 11)) {
			showToast("请输入正确的手机号码(11位)");
			phoneEt.setFocusable(true);
			return;
		}

		if (TextUtils.isEmpty(code)) {
			showToast("验证码不能为空");
			codeEt.setFocusable(true);
			return;
		}

		// captcha（验证码，必填）、mobile_No（手机号，必填）、device_code（设备码，必填）
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "account/nopwd_login");
		map.put("device_code", AppUtils.getmDeviceID());
		map.put("mobile_No", phone);
		map.put("captcha", code);
		getData(map, Task.LOGIN_USER);

	}

	@Override
	public void refresh(Object... param) {
		try {
			int operType = (Integer) param[0];
			Object obj = param[1];
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			switch (operType) {
			case Task.LOGIN_USER: {
				UserDto dto = (UserDto) obj;
				if (dto != null) {
					if ("1".equals(dto.result)) {
						db.modifyConfigItem("uid", dto.uid);
						db.insertUserInfo(dto);
						showToast("恭喜登录成功");
						// 根据入口判断
						if ("0".equals(source) ||"1".equals(source)) {
							Intent it = new Intent(this, MainActivity.class);
							startActivity(it);
							finish();
						}
					} else {
						showToast(dto.message);
					}
				}
			}
				break;

			case Task.GET_CODE:
				UserDto rd = (UserDto) obj;
				if (rd != null) {
					if ("1".equals(rd.result)) {
						Message msg = handler.obtainMessage(REFUSH_TIME);
						msg.arg1 = 60;
						handler.sendMessage(msg);
						showToast("发送验证码成功，请在邮箱查看");
					} else {
						showToast("服务未知错误");
					}
				} else {
					showToast(R.string.about_http_no_net_tip);
				}
				break;

			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*** 读数器 ***/
	private final static int REFUSH_TIME = 0;
	private Handler handler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(Message msg) {

			if (msg.what == REFUSH_TIME) {
				int tc = msg.arg1;
				tc--;
				if (tc >= 0) {
					codeBtn.setText(String.format("已发送(%ds)", tc));
					codeBtn.setTextColor(Color.parseColor("#bfbfbf"));
					codeBtn.setEnabled(false);
					Message m = handler.obtainMessage(REFUSH_TIME);
					m.arg1 = tc;
					handler.sendMessageDelayed(m, 1000);
				} else {
					codeBtn.setText("获取验证码");
					codeBtn.setTextColor(Color.parseColor("#8e8e8e"));
					codeBtn.setEnabled(true);
				}
			}
		}
	};

	protected void onDestory() {
		if (handler != null) {
			handler.removeMessages(REFUSH_TIME);
		}
		super.onDestroy();
	};

}